#!/bin/bash

#Dockerfile、docker-compose.yml、
set -e

# 设置Maven环境变量（解决Jenkins中找不到mvn命令的问题）
export MAVEN_HOME="/Users/zuopeiyu/software/java_about/apache-maven-3.9.6"
export PATH="$MAVEN_HOME/bin:$PATH"

# 验证Maven是否可用
if ! command -v mvn >/dev/null 2>&1; then
    echo "警告: 仍然找不到Maven命令，尝试使用绝对路径"
fi

# 配置参数定义
SERVICE_NAME="pmpu-cat"
SERVICE_PORT="8888"
#REMOTE_HOST="101.201.66.106"
REMOTE_HOST="182.92.233.18"
REMOTE_USER="root"
SERVICE_VERSION="0.0.1-SNAPSHOT"
JDK_VERSION="17"
DOCKER_COMPOSE_PATH="/usr/local/app"

# 打印函数
print_header() {
    echo -e "\033[1m\033[0;34m========================================\033[0m"
    echo -e "\033[1m\033[0;34m$1\033[0m"
    echo -e "\033[1m\033[0;34m========================================\033[0m"
}

print_success() {
    echo -e "\033[0;32m✅ $1\033[0m"
}

print_error() {
    echo -e "\033[0;31m❌ $1\033[0m"
}

print_warning() {
    echo -e "\033[1;33m⚠️ $1\033[0m"
}

print_info() {
    echo -e "\033[0;36mℹ️ $1\033[0m"
}

print_step() {
    echo -e "\033[1m\033[0;35m$1 $2\033[0m"
}

# 静默模式下的简化输出
print_quiet() {
    echo -e "$1"
}

# 构建变量
JAR_FILE="${SERVICE_NAME}-${SERVICE_VERSION}.jar"
REMOTE_SERVICE_DIR="${DOCKER_COMPOSE_PATH}/${SERVICE_NAME}"

print_header "🚀 开始单体架构服务部署 🚀"
print_info "服务名称: $SERVICE_NAME"
print_info "服务端口: $SERVICE_PORT"
print_info "远程主机: $REMOTE_HOST"
print_info "服务版本: $SERVICE_VERSION"

# 1. Maven 构建
print_step "🔨" "开始Maven构建..."

echo "执行命令: mvn clean package -DskipTests"
mvn clean package -DskipTests

BUILD_RESULT=$?

if [[ $BUILD_RESULT -ne 0 ]]; then
    echo -e "\033[0;31m❌ Maven构建失败\033[0m"
    exit 1
fi
echo -e "\033[0;32m✅ Maven构建完成\033[0m"

# 检查JAR文件是否存在
if [[ ! -f "target/$JAR_FILE" ]]; then
    print_error "JAR文件 target/$JAR_FILE 不存在"
    print_warning "请确保Maven构建成功或JAR文件已存在"
    exit 1
fi

# 2. 传输构建文件到远程服务器
print_step "📤" "传输构建文件到远程服务器..."

# 在远程服务器创建必要的目录（如果不存在）
print_quiet "\033[0;36mℹ️ 创建远程目录结构...\033[0m"
CREATE_DIR_CMD="ssh ${REMOTE_USER}@${REMOTE_HOST} \"mkdir -p ${DOCKER_COMPOSE_PATH} && mkdir -p ${REMOTE_SERVICE_DIR}\""
echo "执行命令: $CREATE_DIR_CMD"
ssh "${REMOTE_USER}@${REMOTE_HOST}" "mkdir -p ${DOCKER_COMPOSE_PATH} && mkdir -p ${REMOTE_SERVICE_DIR}"

# 检查远程服务器是否存在 docker-compose.yml 文件
print_quiet "\033[0;36mℹ️ 检查 docker-compose.yml 文件...\033[0m"
if ! ssh "${REMOTE_USER}@${REMOTE_HOST}" "test -f ${DOCKER_COMPOSE_PATH}/docker-compose.yml"; then
    print_quiet "\033[0;36mℹ️ 远程服务器缺少 docker-compose.yml，正在传输...\033[0m"
    SCP_COMPOSE_CMD="scp docker-compose.yml ${REMOTE_USER}@${REMOTE_HOST}:${DOCKER_COMPOSE_PATH}/"
    echo "执行命令: $SCP_COMPOSE_CMD"
    scp "docker-compose.yml" "${REMOTE_USER}@${REMOTE_HOST}:${DOCKER_COMPOSE_PATH}/" >/dev/null 2>&1
    print_quiet "\033[0;32m✅ docker-compose.yml 传输完成\033[0m"
else
    print_quiet "\033[0;36mℹ️ 远程服务器已存在 docker-compose.yml\033[0m"
fi

# 直接传输文件到远程服务目录
print_quiet "\033[0;36mℹ️ 传输 JAR 文件: $JAR_FILE\033[0m"
SCP_JAR_CMD="scp target/$JAR_FILE ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SERVICE_DIR}/"
echo "执行命令: $SCP_JAR_CMD"
scp "target/$JAR_FILE" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SERVICE_DIR}/" >/dev/null 2>&1

print_quiet "\033[0;36mℹ️ 传输 Dockerfile\033[0m"
SCP_DOCKERFILE_CMD="scp Dockerfile ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SERVICE_DIR}/"
echo "执行命令: $SCP_DOCKERFILE_CMD"
scp "Dockerfile" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SERVICE_DIR}/" >/dev/null 2>&1

print_quiet "\033[0;36mℹ️ 传输 配置文件: application.yml\033[0m"
SCP_CONFIG_CMD="scp src/main/resources/application.yml ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SERVICE_DIR}/"
echo "执行命令: $SCP_CONFIG_CMD"
scp "src/main/resources/application.yml" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_SERVICE_DIR}/" >/dev/null 2>&1

print_success "文件传输完成"

# 3. 远程构建Docker镜像并部署
print_step "🚀" "在远程服务器上构建镜像并部署..."

ssh "${REMOTE_USER}@${REMOTE_HOST}" << EOF
set -e

# 进入docker compose目录
cd ${DOCKER_COMPOSE_PATH}

# 1. 停止并删除旧容器
echo -e "\033[1m\033[0;35m🛑 停止并删除旧容器...\033[0m"
echo "执行命令: docker compose stop ${SERVICE_NAME}"
docker compose stop ${SERVICE_NAME} 2>/dev/null || true
echo "执行命令: docker compose rm -f ${SERVICE_NAME}"
docker compose rm -f ${SERVICE_NAME} 2>/dev/null || true

# 2. 删除旧镜像
echo -e "\033[1m\033[0;35m🧹 删除旧镜像...\033[0m"
echo "执行命令: docker rmi ${SERVICE_NAME}:latest"
docker rmi ${SERVICE_NAME}:latest 2>/dev/null || true
echo "执行命令: docker rmi ${SERVICE_NAME}:${SERVICE_VERSION}"
docker rmi ${SERVICE_NAME}:${SERVICE_VERSION} 2>/dev/null || true

# 3. 构建新镜像
echo -e "\033[1m\033[0;35m🐳 构建新Docker镜像...\033[0m"
cd ${REMOTE_SERVICE_DIR}

DOCKER_BUILD_CMD="docker build --build-arg SERVICE_NAME=${SERVICE_NAME} --build-arg SERVICE_VERSION=${SERVICE_VERSION} --build-arg SERVICE_PORT=${SERVICE_PORT} --build-arg JDK_VERSION=${JDK_VERSION} --build-arg TIMEZONE=Asia/Shanghai  -t ${SERVICE_NAME}:${SERVICE_VERSION} --no-cache ."
echo "执行命令: \$DOCKER_BUILD_CMD"

docker build \\
    --build-arg SERVICE_NAME="${SERVICE_NAME}" \\
    --build-arg SERVICE_VERSION="${SERVICE_VERSION}" \\
    --build-arg SERVICE_PORT="${SERVICE_PORT}" \\
    --build-arg TIMEZONE="Asia/Shanghai" \\
    -t ${SERVICE_NAME}:${SERVICE_VERSION} \\
    --no-cache \\
    .

if [[ \$? -ne 0 ]]; then
    echo -e "\033[0;31m❌ Docker镜像构建失败\033[0m"
    exit 1
fi

echo -e "\033[0;32m✅ Docker镜像构建完成\033[0m"

# 4. 启动新容器
cd ${REMOTE_SERVICE_DIR}
echo -e "\033[1m\033[0;35m🚀 启动新服务...\033[0m"
echo "执行命令: docker compose up -d ${SERVICE_NAME}"
docker compose up -d ${SERVICE_NAME}

# 检查容器是否成功启动
if [[ \$? -ne 0 ]]; then
    echo -e "\033[0;31m❌ 容器启动失败\033[0m"
    exit 1
fi

# 等待服务启动
echo -e "\033[1m\033[0;35m⏳ 等待服务启动...\033[0m"
sleep 15

# 检查容器运行状态
echo -e "\033[0;36mℹ️ 检查容器运行状态...\033[0m"
echo "执行命令: docker compose ps ${SERVICE_NAME}"
if ! docker compose ps ${SERVICE_NAME} | grep -q "Up"; then
    echo -e "\033[0;31m❌ 容器未正常运行\033[0m"
    echo -e "\033[0;36m📝 容器日志:\033[0m"
    docker compose logs --tail=50 ${SERVICE_NAME}
    exit 1
fi

echo -e "\033[0;32m✅ 容器运行正常\033[0m"
sleep 15

# 检查服务健康状态
echo -e "\033[1m\033[0;35m🔍 检查服务健康状态...\033[0m"
HEALTH_CHECK_SUCCESS=false
for i in {1..12}; do
    echo "执行命令: curl -f http://localhost:${SERVICE_PORT}/actuator/health"
    if curl -f http://localhost:${SERVICE_PORT}/actuator/health 2>/dev/null; then
        echo -e "\033[0;32m✅ 服务健康检查通过\033[0m"
        HEALTH_CHECK_SUCCESS=true
        break
    fi
    echo -e "\033[1;33m⚠️ 等待服务启动... (\$i/12)\033[0m"
    sleep 10
done

if [[ "\$HEALTH_CHECK_SUCCESS" != "true" ]]; then
    echo -e "\033[0;31m❌ 服务健康检查失败\033[0m"
    echo -e "\033[1;33m⚠️ 服务可能未正常启动，请检查日志\033[0m"
fi

# 显示运行状态
echo -e "\033[1m\033[0;35m📊 容器运行状态:\033[0m"
echo "执行命令: docker compose ps ${SERVICE_NAME}"
docker compose ps ${SERVICE_NAME}

# 显示服务日志（最后20行）
echo -e "\033[1m\033[0;35m📝 服务日志（最后20行）:\033[0m"
echo "执行命令: docker compose logs --tail=20 ${SERVICE_NAME}"
docker compose logs --tail=20 ${SERVICE_NAME}

echo -e "\033[0;32m✅ ${SERVICE_NAME} 部署完成！\033[0m"
echo -e "\033[0;36m🔍 健康检查: http://localhost:${SERVICE_PORT}/actuator/health\033[0m"
EOF

if [[ $? -eq 0 ]]; then
    print_success "🔥 ${SERVICE_NAME} 远程部署成功！"
    echo -e "\033[1m\033[1;37m🌐 服务访问地址:\033[0m \033[0;32mhttp://${REMOTE_HOST}:${SERVICE_PORT}\033[0m"
    echo -e "\033[1m\033[1;37m🔍 健康检查:\033[0m \033[0;32mhttp://${REMOTE_HOST}:${SERVICE_PORT}/actuator/health\033[0m"
else
    print_error "远程部署失败！"
    exit 1
fi

print_header "⭐ 部署完成！⭐" 